/**
 * Bou Scheduler 工具函数
 */

// 显示成功消息
function showSuccess(message, duration = 3000) {
    showNotification(message, 'success', duration);
}

// 显示错误消息
function showError(message, duration = 5000) {
    showNotification(message, 'danger', duration);
}

// 显示警告消息
function showWarning(message, duration = 4000) {
    showNotification(message, 'warning', duration);
}

// 显示信息消息
function showInfo(message, duration = 3000) {
    showNotification(message, 'info', duration);
}

// 显示通知
function showNotification(message, type, duration) {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    notification.style.cssText = `
        top: 20px;
        right: 20px;
        z-index: 9999;
        min-width: 300px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    `;
    
    notification.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 自动移除
    setTimeout(() => {
        if (notification.parentNode) {
            notification.remove();
        }
    }, duration);
}

// 格式化日期时间
function formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '-';
    
    try {
        const date = new Date(dateTimeStr);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
    } catch (e) {
        return dateTimeStr;
    }
}

// 格式化持续时间
function formatDuration(milliseconds) {
    if (!milliseconds || milliseconds < 0) return '0秒';
    
    const seconds = Math.floor(milliseconds / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);

    if (days > 0) return `${days}天 ${hours % 24}小时 ${minutes % 60}分钟`;
    if (hours > 0) return `${hours}小时 ${minutes % 60}分钟`;
    if (minutes > 0) return `${minutes}分钟 ${seconds % 60}秒`;
    return `${seconds}秒`;
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 B';
    
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 获取状态徽章HTML
function getStatusBadge(status) {
    const statusMap = {
        'PENDING': { class: 'bg-warning', text: '待执行' },
        'RUNNING': { class: 'bg-info', text: '执行中' },
        'SUCCESS': { class: 'bg-success', text: '成功' },
        'FAILED': { class: 'bg-danger', text: '失败' },
        'CANCELLED': { class: 'bg-secondary', text: '已取消' },
        'RETRYING': { class: 'bg-warning', text: '重试中' },
        'TIMEOUT': { class: 'bg-danger', text: '超时' }
    };
    
    const statusInfo = statusMap[status] || { class: 'bg-secondary', text: status };
    return `<span class="badge ${statusInfo.class}">${statusInfo.text}</span>`;
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 节流函数
function throttle(func, limit) {
    let inThrottle;
    return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

// 深拷贝对象
function deepClone(obj) {
    if (obj === null || typeof obj !== 'object') return obj;
    if (obj instanceof Date) return new Date(obj.getTime());
    if (obj instanceof Array) return obj.map(item => deepClone(item));
    if (typeof obj === 'object') {
        const clonedObj = {};
        for (const key in obj) {
            if (obj.hasOwnProperty(key)) {
                clonedObj[key] = deepClone(obj[key]);
            }
        }
        return clonedObj;
    }
}

// 验证JSON字符串
function isValidJSON(str) {
    try {
        JSON.parse(str);
        return true;
    } catch (e) {
        return false;
    }
}

// 生成UUID
function generateUUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0;
        const v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

// 复制到剪贴板
async function copyToClipboard(text) {
    try {
        await navigator.clipboard.writeText(text);
        showSuccess('已复制到剪贴板');
    } catch (err) {
        // 降级方案
        const textArea = document.createElement('textarea');
        textArea.value = text;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
        showSuccess('已复制到剪贴板');
    }
}

// 下载文件
function downloadFile(content, filename, contentType = 'text/plain') {
    const blob = new Blob([content], { type: contentType });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);
}

// 导出表格为CSV
function exportTableToCSV(tableId, filename) {
    const table = document.getElementById(tableId);
    if (!table) return;
    
    let csv = [];
    const rows = table.querySelectorAll('tr');
    
    for (let i = 0; i < rows.length; i++) {
        const row = [];
        const cols = rows[i].querySelectorAll('td, th');
        
        for (let j = 0; j < cols.length; j++) {
            let text = cols[j].innerText.replace(/"/g, '""');
            row.push('"' + text + '"');
        }
        
        csv.push(row.join(','));
    }
    
    downloadFile(csv.join('\n'), filename, 'text/csv');
}

// 检查网络状态
function checkNetworkStatus() {
    if (!navigator.onLine) {
        showWarning('网络连接已断开');
        return false;
    }
    return true;
}

// 添加网络状态监听
if (typeof window !== 'undefined') {
    window.addEventListener('online', () => {
        showSuccess('网络连接已恢复');
    });
    
    window.addEventListener('offline', () => {
        showWarning('网络连接已断开');
    });
}

/**
 * 生成清理任务的时间参数
 * @param {number} hoursAgo - 多少小时前，默认1小时
 * @returns {string} 格式化的时间字符串 YYYY-MM-DDTHH:mm:ss
 */
function generateCleanupTime(hoursAgo = 1) {
    const now = new Date();
    const targetTime = new Date(now.getTime() - hoursAgo * 60 * 60 * 1000);
    
    // 格式化为 YYYY-MM-DDTHH:mm:ss 格式，使用本地时间
    const year = targetTime.getFullYear();
    const month = String(targetTime.getMonth() + 1).padStart(2, '0');
    const day = String(targetTime.getDate()).padStart(2, '0');
    const hours = String(targetTime.getHours()).padStart(2, '0');
    const minutes = String(targetTime.getMinutes()).padStart(2, '0');
    const seconds = String(targetTime.getSeconds()).padStart(2, '0');
    
    const formattedTime = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
    
    // 调试信息
    console.log('清理时间参数:', {
        now: now.toLocaleString('zh-CN'),
        targetTime: targetTime.toLocaleString('zh-CN'),
        formattedTime: formattedTime,
        hoursAgo: hoursAgo
    });
    
    return formattedTime;
}

/**
 * 清理已完成任务的通用函数
 * @param {number} hoursAgo - 清理多少小时前的任务，默认1小时
 * @param {Function} onSuccess - 成功回调函数
 * @param {Function} onError - 错误回调函数
 */
function globalCleanupCompletedTasks(hoursAgo = 1, onSuccess, onError) {
    if (!confirm('确定要清理所有已完成任务吗？此操作不可逆。')) {
        return;
    }
    
    const beforeTime = generateCleanupTime(hoursAgo);
    
    fetch(`/api/tasks/cleanup?beforeTime=${beforeTime}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const message = `已完成任务清理成功！共清理 ${data.data} 个任务`;
            showSuccess(message);
            if (onSuccess) onSuccess(data);
        } else {
            const errorMessage = '清理失败: ' + data.message;
            showError(errorMessage);
            if (onError) onError(errorMessage);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        const errorMessage = '清理失败，请检查网络连接';
        showError(errorMessage);
        if (onError) onError(errorMessage);
    });
}
